// 退出编辑事件
import { useStore } from "@/store"
import { Ref } from "vue-demi"
function useStopEdit(btnLoading: Ref<boolean>) {
  const store = useStore()
  const stopEdit = async () => {
    if (
      store.state.markdown.oldContent !== store.state.markdown.content &&
      store.state.editor.editMode === "editable"
    ) {
      store
        .dispatch("editor/asyncChangeMode")
        .then(async () => {
          btnLoading.value = true
          await store.dispatch("markdown/saveDoc")
          await store.dispatch("editor/stopEdit", {
            fileId: store.state.markdown.id,
          })
          btnLoading.value = false
        })
        .catch(async (action) => {
          if (action === "cancel") {
            await store.dispatch("editor/stopEdit", {
              fileId: store.state.markdown.id,
            })
            store.commit(
              "markdown/changeContent",
              store.state.markdown.oldContent
            )
          }
        })
    } else {
      btnLoading.value = true
      await store.dispatch("editor/stopEdit", {
        fileId: store.state.markdown.id,
      })
      btnLoading.value = false
    }
  }
  return { stopEdit }
}
export default useStopEdit
